package com.macaupass.sdkDemo

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.support.v4.app.FragmentActivity
import android.text.TextUtils
import android.view.View
import android.view.View.OnClickListener
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.RadioButton
import android.widget.Toast
import com.macau.pay.sdk.OpenSdk
import com.macau.pay.sdk.base.ConstantBase
import com.macau.pay.sdk.base.PayResult
import com.macau.pay.sdk.define.OpenSDKBaseUrl
import com.macau.pay.sdk.interfaces.OpenSdkInterfaces
import com.macau.pay.sdk.util.Logger
import okhttp3.*
import org.json.JSONObject
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*

class NewMainActivity : FragmentActivity(), OnClickListener, OpenSdkInterfaces,
    TipDialogFragment.IActionDialogResultListener {


    private var tipDialogFragment: TipDialogFragment? = null
    private val respCreateAllPayOrderSucceed = 1

    var rbSit: RadioButton? = null
    var rbUat: RadioButton? = null
    var rbPrd: RadioButton? = null
    private var btnPayAli: LinearLayout? = null
    private var btnPayMacau: LinearLayout? = null
    private var btnMpayNew: LinearLayout? = null
    private var btnPayWeChat: LinearLayout? = null
    private var weChatOrderBean: WeChatOrderResult? = null
    private var btnRefund: LinearLayout? = null
    private var evAppId: EditText? = null
    private var evCommodityName: EditText? = null
    private var evOrderAmout: EditText? = null
    private var mActivity: Activity? = null
    private var etWeChatServiceOrderAppId: EditText? = null
    private var etWeChatAppId: EditText? = null
    private var ev_mername: EditText? = null
    private var ev_merid: EditText? = null
    private var ev_merinfo: EditText? = null
    private var ev_app_url: EditText? = null
    private var ev_app_hanye: EditText? = null
    var mpay_url: String = ""
    var alipay_url: String = ""
    var wechat_url: String = "";

    private var demoUrl_sit = "http://14.29.69.182:40052/sit_mpay/merchantSign.do";
    private var demoUrl_uat = "https://uatqr.macaupay.com.mo/mpay/merchantSign.do";
    private var demoUrl_pro = "https://qr.macaupay.com.mo/mpay/merchantSign.do";
    private var orderurl = "";

    private val mHandler = Handler(Handler.Callback { msg ->
        var result: String
        when (msg.what) {
            respCreateAllPayOrderSucceed -> {
                result = msg.obj as String
                // 调起alipay收银台.........
                Logger.i("返回的内容----$result")
                try {
                    OpenSdk.newPayAll(this@NewMainActivity, result, this@NewMainActivity)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
        false
    })

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_new_main)
        mActivity = this
//        reqOrderInfo()
        initView()
        tipDialogFragment = TipDialogFragment.newInstance()
        tipDialogFragment!!.registerOnClickListener(this)
    }

    private fun initView() {


        btnPayAli = findViewById(R.id.tb_trade_confirm_pay_ali)
        btnPayMacau = findViewById(R.id.tb_trade_confirm_pay_macau)
        btnMpayNew = findViewById(R.id.tb_trade_confirm_pay_macau_new)
        btnPayWeChat = findViewById(R.id.tb_trade_confirm_pay_wechat)
        btnRefund = findViewById(R.id.btn_refund)
        btnRefund?.setOnClickListener(this)
        btnPayWeChat!!.setOnClickListener(this)
        btnPayAli!!.setOnClickListener(this)
        btnPayMacau!!.setOnClickListener(this)
        btnMpayNew?.setOnClickListener(this)
        evAppId = findViewById(R.id.ev_app_id)
        evOrderAmout = findViewById(R.id.ev_order_amout)
        evCommodityName = findViewById(R.id.ev_app_name)
        etWeChatAppId = findViewById(R.id.ev_wechat_appid)
        etWeChatServiceOrderAppId = findViewById(R.id.ev_wechat_service_appid)

        ev_mername = findViewById(R.id.ev_mername)
        ev_merid = findViewById(R.id.ev_merid)
        ev_merinfo = findViewById(R.id.ev_merinfo)
        ev_app_url = findViewById(R.id.ev_app_url)
        ev_app_hanye = findViewById(R.id.ev_app_hanye)

        // 在调起sdk时要设置sdk使用的环境,默认UAT环境 // 0 ：生产，1：250，2 :UAT

        rbSit = findViewById(R.id.rb_sit)
        rbUat = findViewById(R.id.rb_uat)
        rbPrd = findViewById(R.id.rb_prd)
        rbSit!!.isChecked = true
        rbSit!!.setOnClickListener(this)
        rbUat!!.setOnClickListener(this)
        rbPrd!!.setOnClickListener(this)


        OpenSdk.setMPayAppId(ConstantBase.ConnectUrl_SIT)
        OpenSdk.setEnvironmentType(ConstantBase.ConnectUrl_SIT)
    }

    private fun reqOrderInfo() {
        val requestMap = JSONObject()
        requestMap.put("order_id", "849");
        requestMap.put("type", "5");
        val param = requestMap.toString()
        val body = RequestBody.create(JSON, param)

        val request = Request.Builder()
            .url("http://chaoshi.zgxiaochengxu.com/api/shop/pay/pay?token=1b375e78-52b3-430b-96c7-7a2fdc2cd21f")
            .post(body)
            .removeHeader("User-Agent")
            .addHeader("Content-Type", "application/json")
            .addHeader("accept", "*/*")
            .addHeader("connection", "Keep-Alive")
            .build()
        OkHttpClient().newCall(request).enqueue(object : Callback {
            override fun onFailure(p0: Call, p1: IOException) {
//                TODO("Not yet implemented")
            }

            override fun onResponse(p0: Call, p1: Response) {
                mHandler.post(Runnable {
                    kotlin.run {
                        if (p1.code() == 200) {
                            val result = p1.body()!!.string()
                            Logger.i("返回的内容----$result")
                            val resultObj = JSONObject(result)
                            Toast.makeText(
                                mActivity,
                                resultObj.getString("msg"),
                                Toast.LENGTH_SHORT
                            ).show()
                        } else {
                            Toast.makeText(mActivity, p1.message(), Toast.LENGTH_SHORT).show()
                        }
                    }
                })
            }
        })
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.tb_trade_confirm_pay_macau -> try {
                allPay("mpay")
            } catch (e: Exception) {
                // TODO Auto-generated catch block
                e.printStackTrace()
            }
            R.id.tb_trade_confirm_pay_macau_new -> try {
                allPay("mpay")
            } catch (e: Exception) {
                // TODO Auto-generated catch block
                e.printStackTrace()
            }
            R.id.btn_refund -> try {
                doRefund()
            } catch (e: Exception) {
                e.printStackTrace()
            }
            R.id.tb_trade_confirm_pay_ali -> try {
                allPay("alipay")
            } catch (e: Exception) {
                // TODO Auto-generated catch block
                e.printStackTrace()
            }

            R.id.tb_trade_confirm_pay_wechat -> try {
                allPay("wechat")
            } catch (e: Exception) {
                // TODO Auto-generated catch block
                e.printStackTrace()
            }
            R.id.rb_sit -> {
                orderurl = demoUrl_sit;
                OpenSdk.setMPayAppId(ConstantBase.ConnectUrl_SIT)
                OpenSdk.setEnvironmentType(ConstantBase.ConnectUrl_SIT)
            }
            R.id.rb_uat -> {
                orderurl = demoUrl_uat;
                OpenSdk.setMPayAppId(ConstantBase.ConnectUrl_UAT)
                OpenSdk.setEnvironmentType(ConstantBase.ConnectUrl_UAT)
            }
            R.id.rb_prd -> {
                orderurl = demoUrl_pro;
                OpenSdk.setMPayAppId(ConstantBase.ConnectUrl_PRD)
                OpenSdk.setEnvironmentType(ConstantBase.ConnectUrl_PRD)
            }
            else -> {
            }
        }
    }


    private fun allPay(pay_channel: String) {
        if (evAppId!!.text.toString().length == 0) {
            Toast.makeText(this, "org_id 不能爲空", Toast.LENGTH_LONG).show();
            return;
        }
        if (evOrderAmout!!.text.toString().length == 0) {
            Toast.makeText(this, "total_fee 不能爲空", Toast.LENGTH_LONG).show();
            return;
        }
        if (evCommodityName!!.text.toString().length == 0) {
            Toast.makeText(this, "body 不能爲空", Toast.LENGTH_LONG).show();
            return;
        }
        if (ev_mername!!.text.toString().length == 0) {
            Toast.makeText(this, "sub_merchant_id 不能爲空", Toast.LENGTH_LONG).show();
            return;
        }
        if (ev_merinfo!!.text.toString().length == 0) {
            Toast.makeText(this, "sub_merchant_id 不能爲空", Toast.LENGTH_LONG).show();
            return;
        }
        if (ev_app_url!!.text.toString().length != 0) {
//            http://14.29.69.182:40052/masl/umpg/gateway/
//            https://uatopenapi.macaupay.com.mo/masl/umpg/gateway
            OpenSDKBaseUrl.OPEN_URL_SIT = ev_app_url!!.text.toString()
        }
        val requestMap = JSONObject()
/* demo 原有参数 */
        /*requestMap.put("org_id", System.currentTimeMillis().toString())//evAppId!!.text.toString()
        requestMap.put("sign_type", "MD5")
        requestMap.put("pay_channel", pay_channel)
        requestMap.put("total_fee", evOrderAmout!!.text.toString())
        requestMap.put("body", evCommodityName!!.text.toString())
        requestMap.put("sub_appid", etWeChatServiceOrderAppId!!.text.toString())
        requestMap.put("subject", ev_merinfo!!.text.toString())
        val innerMsg = JSONObject()*/
//        innerMsg.put("sub_merchant_name", ev_mername!!.text.toString())
//        innerMsg.put("sub_merchant_id", ev_merid!!.text.toString())
//        innerMsg.put("sub_merchant_industry", ev_app_hanye!!.text.toString())
/* demo 原有参数 */
/* 澳门通参数 */
//        requestMap.put("sign", "1595BAAA643A215DD0A644A502C47A94")
//        requestMap.put("format", "JSON")
//        requestMap.put("timestamp", "1605924905")
//        requestMap.put("nonce_str", "693245eef48cfc18fd72fb9f2d5bc938")
//        requestMap.put("version", "1.1.0")
        requestMap.put("out_trans_id", System.currentTimeMillis().toString())
        requestMap.put("currency", "MOP")
        requestMap.put("product_code", "MP_APP_PAY")
        requestMap.put("channel_type", "1")
        requestMap.put(
            "service",
            "mpay.trade.mobile.pay"
        )  //mpay.online.trade.precreate   MPay.trade.mobile.pay
        requestMap.put("org_id", "888534816729449")
        requestMap.put("sign_type", "MD5")
        ////            公共参数
        requestMap.put("pay_channel", "mpay")
        requestMap.put("total_fee", "0.1")
        requestMap.put("body", evCommodityName!!.text.toString())
        requestMap.put("subject", "订单支付")
        val innerMsg = JSONObject()
        innerMsg.put("sub_merchant_name", "3Q Mall")
        innerMsg.put("sub_merchant_id", "888534816729449") //888534816729449    888534816458841
        innerMsg.put("sub_merchant_industry", "4816")
        /* 澳门通参数 */

        requestMap.put("extend_params", innerMsg);
        val param = requestMap.toString()
        Logger.d(param);
        val body = RequestBody.create(JSON, param)
        Logger.d("body=====", param);
        Logger.d("orderurl=====", orderurl);
        val request = Request.Builder()
            .url(orderurl)
            .post(body)
            .removeHeader("User-Agent")
            .addHeader("Content-Type", "application/json")
            .addHeader("accept", "*/*")
            .addHeader("connection", "Keep-Alive")
            .build()
        OkHttpClient().newCall(request).enqueue(object : Callback {
            val mMainHandler: Handler = Handler(mActivity!!.mainLooper)
            override fun onFailure(p0: Call, p1: IOException) {
                mMainHandler.post(Runnable {
                    kotlin.run {
                        Toast.makeText(
                            mActivity,
                            p1.message,
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                })
            }

            override fun onResponse(p0: Call, response: Response) {
                mHandler.post(Runnable {
                    kotlin.run {
                        if (response.code() == 200) {
                            val result1 = response.body()!!.string()
                            Logger.e(result1);
                            val resultObj = JSONObject(result1)
                            Logger.i("resultObj----$resultObj")
                            val respCode = resultObj.getString("respCode")
                            val respMsg = resultObj.getString("respMsg")

                            if (respCode.equals("0000")) {
                                //Logger.i("signData----$signData")
                                if (pay_channel.equals("wechat")) {
                                    if (!checkApkExist(this@NewMainActivity, "com.tencent.mm")) {
                                        Toast.makeText(
                                            this@NewMainActivity,
                                            "未安裝微信",
                                            Toast.LENGTH_SHORT
                                        ).show()
                                    } else {
                                        val signData = resultObj.getString("signData")
                                        val message = mHandler.obtainMessage()
                                        message.what = respCreateAllPayOrderSucceed
                                        message.obj = signData
                                        mHandler.sendMessage(message)
                                    }
                                } else {
                                    val signData = resultObj.getString("signData")
                                    val message = mHandler.obtainMessage()
                                    message.what = respCreateAllPayOrderSucceed
                                    message.obj = signData
                                    mHandler.sendMessage(message)
                                }

                            } else {
                                Toast.makeText(this@NewMainActivity, respMsg, Toast.LENGTH_LONG)
                                    .show()
                            }
                        }
                    }
                })

            }
        })

    }

    private fun doRefund() {
        val requestMap = JSONObject()
        requestMap.put("app_id", etWeChatServiceOrderAppId!!.text.toString())
        requestMap.put("api_name", "refund")
        requestMap.put("biz_api_code", "200020006")
        requestMap.put("data_type", "JSON")
        requestMap.put("charset", "utf-8")
        requestMap.put("timestamp", SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date()))
        requestMap.put("sign_type", "RSA")
        requestMap.put("version", "1.0")
        val innerMsg = JSONObject()
        innerMsg.put("trade_no", weChatOrderBean!!.Data.trade_no)
        innerMsg.put("out_request_no", "")
        innerMsg.put("refund_amount", evOrderAmout!!.text.toString())
        innerMsg.put("refund_reason", "退款")
        innerMsg.put("operator_id", "Yx_001")
        innerMsg.put("store_id", "NJ_001")
        innerMsg.put("terminal_id", "NJ_T_001")
        requestMap.put("biz_content", innerMsg)
        val param = requestMap.toString()
        val body = RequestBody.create(JSON, param)
        val request = Request.Builder()
            .url(wechat_url)
            .post(body)
            .removeHeader("User-Agent")
            .addHeader("User-Agent", "macaupay")
            .addHeader("Content-Type", "application/json")
            .addHeader("accept", "*/*")
            .addHeader("connection", "Keep-Alive")
            .build()
        OkHttpClient().newCall(request).enqueue(object : Callback {
            val mHandler: Handler = Handler(mActivity!!.mainLooper)
            override fun onFailure(p0: Call, p1: IOException) {
                mHandler.post(Runnable {
                    kotlin.run {
                        Toast.makeText(mActivity, p1.message, Toast.LENGTH_SHORT).show()
                    }
                })

            }

            override fun onResponse(p0: Call, response: Response) {
                mHandler.post(Runnable {
                    kotlin.run {
                        if (response.code() == 200) {
                            val result = response.body()!!.string()
                            Logger.i("返回的内容----$result")
                            val resultObj = JSONObject(result)
                            Toast.makeText(
                                mActivity,
                                resultObj.getString("respMsg"),
                                Toast.LENGTH_SHORT
                            ).show()
                        } else {
                            Toast.makeText(mActivity, response.message(), Toast.LENGTH_SHORT).show()
                        }
                    }
                })

            }
        })
    }

    val JSON = MediaType.parse("application/json; charset=utf-8")


    fun checkApkExist(ctx: Context, packageName: String?): Boolean {

        if (packageName == null || "" == packageName) {
            return false
        }
        try {
            val info = ctx.packageManager.getApplicationInfo(
                packageName,
                PackageManager.GET_UNINSTALLED_PACKAGES
            )
            return if (info != null) {
                true
            } else {
                false
            }
        } catch (e: PackageManager.NameNotFoundException) {
            return false
        }

    }


    private var message: Message? = null

    // 使用支付寶支付后回調狀態碼
    // 9000 订单支付成功
    // 8000 正在处理中，支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态 .(支付宝服务端返回的错误码)
    // 4000 订单支付失败
    // 6001 用户中途取消
    // 6002 网络连接出错
    // 6004 支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态 。（支付宝客户端不能得到服务端的响应，往往是因为网络原因）
    // 1000 签名失败
    // 其它 其它支付错误
    override fun AliPayInterfaces(payResult: PayResult) {
        Logger.d("ResultStatus===" + payResult?.resultStatus)
        if (!TextUtils.isEmpty(payResult!!.resultStatus)) {
            goResult(payResult?.resultStatus, 0)
        } else {
            Toast.makeText(mActivity, "直接结果为空", Toast.LENGTH_SHORT).show()
        }
    }

    fun goResult(result: String, type: Int) {
        val intent = Intent(this, ResultActivity::class.java)
        when (type) {
            0 -> {
                intent.putExtra("result", "支付寶支付--" + result)
            }
            1 -> {
                intent.putExtra("result", "MPay支付--" + result)
            }
            2 -> {
                intent.putExtra("result", "微信支付--" + result)
            }
            3 -> {
                intent.putExtra("result", "异常信息--" + result)
            }
        }
        mActivity?.startActivity(intent)
    }

    // 澳门通
    // 9000 :支付成功,6002: 网络连接出错,6001: 用户中途取消,4000
    // :订单支付失败，5000：支付异常,4004:无效订單,1000:簽名失敗,0001:手續費大於交易金額,4044:訂單金額無效

    override fun MPayInterfaces(payResult: PayResult) {
        Logger.d("ResultStatus===" + payResult?.resultStatus)
        if (!TextUtils.isEmpty(payResult?.resultStatus)) {
            var result: String = "";
            if (payResult?.resultStatus.equals("9000")) {
                result = "支付成功,code:9000"
            } else if (payResult?.resultStatus.equals("5000")) {
                result = "支付结果未知,导致该问题是因为进程间通信出现了bug导致,可能是用户取消了支付,或者支付成功了,需要第三方对该订单进行结果查询,code:5000"
            } else if (payResult?.resultStatus.equals("6001")) {
                result = "支付取消,code:6001"
            }
            Toast.makeText(mActivity, "结果---" + result, Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(mActivity, "直接结果为空", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 微信支付
     */
    override fun WeChatPayInterfaces(payResult: PayResult) {
        Logger.d("ResultStatus===" + payResult?.resultStatus)
        if (!TextUtils.isEmpty(payResult?.resultStatus)) {
            goResult(payResult?.resultStatus, 2)
        } else {
            Toast.makeText(mActivity, "直接结果为空", Toast.LENGTH_SHORT).show()
        }
    }

    override fun OpenSDKInterfaces(payResult: PayResult?) {
        Logger.d("ResultStatus===" + payResult?.resultStatus)
        if (!TextUtils.isEmpty(payResult!!.resultStatus)) {
            goResult(payResult?.resultStatus, 3)
        } else {
            Toast.makeText(mActivity, "直接结果为空", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onActionDialogResult(action: Int) {
        if (action == 0) {
            mHandler.sendMessage(message)
        }
    }

}
